package de.projectgoodmorning.alarm.model.gateway;

import java.util.Calendar;

import junit.framework.TestCase;
import de.projectgoodmorning.alarm.model.generic.Alarm;

public class CombinedAlarmTest extends TestCase {

	private Alarm alarm;
	private CombinedAlarm combinedAlarm;
	
	protected void setUp() throws Exception {
		super.setUp();
		alarm = new Alarm( 
				Calendar.getInstance().getTimeInMillis(), null );
		combinedAlarm = new CombinedAlarm( alarm );
	}

	public void test_it_should_have_a_mainalarm() {
		try {
			new CombinedAlarm( null );
			fail();
		} catch( IllegalArgumentException e ) {
		}
	}
	
	public void test_it_should_add_alarm() {
		combinedAlarm.addAlarm( 0, 100 );
		assertTrue( combinedAlarm.getGatewayAlarms().length == 1 );
		
		GatewayAlarm[] alarms = combinedAlarm.getGatewayAlarms();
		assertTrue( alarms[0].seconds == 0 );
		assertTrue( alarms[0].color == 100 );
	}
	
	public void test_it_should_remove_alarm() {
		combinedAlarm.addAlarm( 0, 0 );
		combinedAlarm.removeAlarm( 0 );
		assertTrue( combinedAlarm.getGatewayAlarms().length == 0 );
	}
	
	public void test_it_should_remove_all_alarms() {
		combinedAlarm.addAlarm( 0, 0 );
		combinedAlarm.addAlarm( 0, 0 );
		combinedAlarm.addAlarm( 0, 0 );
		
		combinedAlarm.removeAllAlarms();
		assertTrue( combinedAlarm.getGatewayAlarms().length == 0 );
	}
	
	public void test_it_should_get_state_by_all_alarms() {
		combinedAlarm.addAlarm( 0, 0 );
		combinedAlarm.addAlarm( 0, 0 );
		
		Alarm[] alarm = combinedAlarm.getGatewayAlarms();

		alarm[1].state = Alarm.ACTIVE;
		assertTrue( combinedAlarm.getState() == Alarm.ACTIVE );
		
		alarm[1].state = Alarm.INACTIVE;
		assertTrue( combinedAlarm.getState() == Alarm.INACTIVE );
	}
	
	public void test_it_should_export_all_alarms() {
		combinedAlarm.addAlarm( 5, 0 );
		combinedAlarm.addAlarm( -10, 0 );
		
		Alarm[] alarm = combinedAlarm.exportAll();
		assertTrue( alarm.length == combinedAlarm.getGatewayAlarms().length + 1 );
	}
	
	public void test_it_should_set_moment_by_export_all_alarms() {
		combinedAlarm.addAlarm( 5, 0 );
		combinedAlarm.addAlarm( -10, 0 );
		
		Calendar expectedMoment = Calendar.getInstance();
		long main = combinedAlarm.getMainAlarm().getMoment();
		Alarm[] alarm = combinedAlarm.exportAll();
		
		expectedMoment.setTimeInMillis( main );
		expectedMoment.add( Calendar.SECOND, 5 );
		assertTrue( isAround( alarm[0].getMoment(), expectedMoment.getTimeInMillis(), 100 ) );
		
		expectedMoment.setTimeInMillis( main );
		expectedMoment.add( Calendar.SECOND, -10 );
		assertTrue( isAround( alarm[1].getMoment(), expectedMoment.getTimeInMillis(), 100 ) );
	}
	
	
	private boolean isAround( long value, long expected, int variance ) {
		if( value < expected - variance || value > expected + variance ) {
			return false;
		} else {
			return true;
		}
	}
}
